const id = location.search.split("=")[1];

// 方法一：获取所有商品数据，前端筛选（不推荐）
// 方法二：根据id请求后端接口，直接获取指定数据（后端筛选）（推荐）
ajax("http://localhost:3000/api",res=>{
    res = JSON.parse(res).msg;
    let i = 0;
    res.some((val,idx)=>{
        i = idx;
        return val.proId === id
    })
    // 渲染小图
    $(".big>img").src = res[i].img;
    // 渲染大图
    $(".big>img").src = res[i].img;
    // 渲染超大图
    $(".enlarge>img").src = res[i].img;
    // 渲染图片列表
    let str = "";
    res[i].imgs.forEach(val=>{
        str += `<div class="simg"><img src="${val}" alt=""></div>`
    })
    $(".sw_wrap").innerHTML = str;
    // 渲染标题
    $(".proName").innerHTML=res[i].proName;
    $(".brand>span").innerHTML = res[i].brand;
    $(".kind>span").innerHTML = res[i].kind;
    $(".storage>span").innerHTML = res[i].storage;
    $(".sales>span").innerHTML = res[i].sales;
    // 计算并渲染现价
    $(".price>span").innerHTML = "￥" + res[i].price;
    console.log(res[i].proId)
    new Magnifier({
        left:document.getElementById("left"),
        cart:document.querySelector(".cart"),
        right:document.getElementById("right"),
        sBox:document.querySelector(".big"),
        sBspan:document.querySelector(".mask"),
        bBox:document.querySelector(".enlarge"),
        sBimg:document.querySelector(".big img"),
        bBimg:document.querySelector(".enlarge img"),
        imgBox:document.querySelector(".sw_wrap"),
        imgs:document.querySelectorAll(".sw_wrap img"),
        wrap:document.querySelector(".sw_wrap"),
        id:res[i].proId,
        price:res[i].price
    })
},{
    type:"getGoods"
})
function $(s){
    return document.querySelector(s);
}
function ajax(url, callback, data){
    let str = "";
    for(let i in data){
        str += `${i}=${data[i]}&`
    }
    url += "?" + str;
    const xhr = new XMLHttpRequest();
    xhr.open("get",url)
    xhr.onload = function(){
        if(xhr.status === 200){
            callback(xhr.responseText)
        }
    }
    xhr.send();
}
function Magnifier(ops){
    this.wrap = ops.wrap;
    this.left = ops.left;
    this.right = ops.right;
    this.sBspan = ops.sBspan;
    this.cart = ops.cart;
    this.mask = ops.mask;
    this.sBox = ops.sBox;
    this.bBox = ops.bBox;
    this.sBimg = ops.sBimg;
    this.bBimg = ops.bBimg;
    this.imgBox = ops.imgBox;
    this.imgs = ops.imgs;
    this.price = ops.price;
    this.id = ops.id;
    this.imgBox.style.width = (this.imgs.length+1)*this.imgs[0].offsetWidth +"px";
    this.index = 0;
    this.addEvent();
    console.log(this.id,this.price)
}
Magnifier.prototype.addEvent = function(){
    const _this = this;
    this.sBox.onmouseenter = function(){
        _this.show();
    }
    this.sBox.onmouseleave = function(){
        _this.hide();
    }
    this.sBox.onmousemove = function(eve){
        const e = eve||window.event;
        _this.move(e); 
    }
    this.left.onclick = function(){
        _this.leftChangeIndex();
    }
    this.right.onclick = function(){
        _this.rightChangeIndex();
    }
    this.cart.onclick = function (){
        _this.setLocal(_this.id,_this.price)
    }
    this
    for(let i=0;i<this.imgs.length;i++){
        this.imgs[i].onclick = ()=>{
            for(var j=0;j<this.imgs.length;j++){
                this.imgs[j].style.border = "1px solid #EFF0F5";
            }
            console.log(i);
            this.bBimg.src = this.sBimg.src = this.imgs[i].src;
            this.imgs[i].style.border = "1px solid red"
        }
    }
}
Magnifier.prototype.setLocal = function(id,price){
    const goods = localStorage.getItem("goods") ? JSON.parse(localStorage.getItem("goods")) : [];

    if(goods.length < 1){
        goods.push({
            id:id,
            num:1,
            price:price
        })
    }else{
        let i = 0;
        const flag = goods.some((val,idx)=>{
            i = idx;
            return val.id === id
        })
        if(flag){
            goods[i].num++;
        }else{
            goods.push({
                id:id,
                num:1,
                price:price
            })
        }
    }
    localStorage.setItem("goods", JSON.stringify(goods))
}
Magnifier.prototype.rightChangeIndex = function(){
    this.render();
}
Magnifier.prototype.leftChangeIndex = function(){
    this.render2();
}
Magnifier.prototype.render = function(){
    move(this.imgBox,{
        left:-this.index*80 + "px"
    })
}
Magnifier.prototype.render2 = function(){
    move2(this.imgBox,{
        left:-this.index*80 + "px"
    })
}
Magnifier.prototype.show = function(){
    this.bBox.style.display = "block";
    this.sBspan.style.display = "block";
    this.sBspan.style.width = this.sBox.offsetWidth/(this.bBimg.offsetWidth/this.bBox.offsetWidth)+"px";
    this.sBspan.style.height = this.sBox.offsetHeight/(this.bBimg.offsetHeight/this.bBox.offsetHeight)+"px";
}
Magnifier.prototype.hide = function(){
    this.bBox.style.display = "none";
    this.sBspan.style.display = "none";
}
function move(ele, data){
        for(let i in data){
            let now = parseInt(getStyle(ele, i));
            let speed = 40;
            ele.style[i] = now - speed + "px";
            if(data[i] !== now){
                flag = false;
            }
        }
}
function move2(ele, data){
        for(let i in data){
            let now = parseInt(getStyle(ele, i));
            let speed = 40;
            ele.style[i] = now + speed + "px";
            if(data[i] !== now){
                flag = false;
            }
        }
}
function getStyle(ele, attr){
    if(getComputedStyle){
        return getComputedStyle(ele)[attr];
    }else{
        return ele.currentStyle[attr];
    }
}
Magnifier.prototype.move = function(e){
    let L = e.pageX -(this.sBox.offsetWidth /2)- this.sBspan.offsetWidth +255 ;
    let T = e.pageY -this.sBox.offsetHeight- this.sBspan.offsetHeight/2 +200;
    if(L < 0) L = 0;
    if(T < 0) T = 0;
    if(L > this.sBox.offsetWidth - this.sBspan.offsetWidth){
        L = this.sBox.offsetWidth - this.sBspan.offsetWidth
    }
    if(T > this.sBox.offsetHeight - this.sBspan.offsetHeight){
        T = this.sBox.offsetHeight - this.sBspan.offsetHeight
    }
    this.sBspan.style.left = L + "px";
    this.sBspan.style.top = T + "px";
    let X = L/(this.sBox.offsetWidth -  this.sBspan.offsetWidth);
    let Y = T/(this.sBox.offsetHeight - this.sBspan.offsetHeight);
    this.bBimg.style.left = (this.bBox.offsetWidth-this.bBimg.offsetWidth)*X+"px";
    this.bBimg.style.top = (this.bBox.offsetHeight-this.bBimg.offsetHeight)*Y+"px";
}